<?php
/**
 * Created by PhpStorm.
 * User: suncco
 * Date: 2018/8/13
 * Time: 14:50
 */

namespace app\admin\controller;


class Banner extends Base
{
    public function index(){
        $banner = db('banner');

        $orderby = 't desc';

        $list = $banner
            ->order($orderby)
            ->select();

//        dump( Db::getLastSql());die;

        $this->assign('list', $list);
        return view();
    }

    public function add(){
        return view('form');
    }

    public function edit(){
        $banner_id = input('banner_id');
        $banner = db('banner');

        $banner = $banner
            ->where('banner_id',$banner_id)
            ->find();

        $this->assign('banner',$banner);
        return view('form');
    }

    public function update(){
        $info = input('post.');
        $banner_id = intval($info['banner_id']);
        $data['banner_title'] = isset($info['banner_title']) ? $info['banner_title'] : false;
        $data['banner_url'] = isset($info['banner_url']) ? $info['banner_url'] : false;
        $data['banner_img'] = $info['banner_img'];
        $data['t'] = time();
        if ($banner_id) {
            $act = 'add';
        }else{
            $act = 'edit';
            $data['banner_id'] = $banner_id;
        }

        $validate = $this->validate($data, 'Banner.'.$act, [], true);
        if ($validate !== true) {
            return json(['flag'=>1,'message'=>'警告！Banner名称、链接、图片为必填项目。']);
        }

        if ($banner_id) {
            db('banner')->data($data)->where('banner_id=' . $banner_id)->update();
            addlog('编辑Banner，Links_ID：' . $banner_id);
            return json(['flag'=>0,'message'=>'恭喜！Banner编辑成功！']);
        } else {
            $links_id = db('banner')->data($data)->insert();
            if ($links_id) {
                addlog('新增Banner，Banner_ID：' . $banner_id);
                return json(['flag'=>0,'message'=>'恭喜！Banner新增成功！']);
            } else {
                return json(['flag'=>1,'message'=>'抱歉，未知错误！']);
            }

        }
    }

    public function del(){
        $banner_id = input('banner_id');
        $banner_id = isset($banner_id) ? $banner_id : false;

        if ($banner_id) {
            if (strpos($banner_id, ',')) {

//                $links_id = implode(',', $links_id);
                $map = [['banner_id','in',$banner_id],];
            } else {

                $map = 'banner_id=' . $banner_id;
            }
            if (db('banner')->where($map)->delete()) {
                addlog('删除Banner，Banner_ID：' . $banner_id);
                return json(['flag'=>0,'message'=>'恭喜，友链删除成功！']);
            } else {
                return json(['flag'=>1,'message'=>'删除失败！']);
            }
        } else {
            return json(['flag'=>1,'message'=>'参数错误！']);
        }
    }
}